package com.jiufen.Utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Component
@Slf4j
public class UploadUtils {
   /*
   //成员变量
    @Value("${tencent.cos.prootocol}")
    private String prootocol;
    @Value("${tencent.cos.bucketName}")
    private String bucketName;
    @Value("${tencent.cos.Region}")
    private String regionCode;
    @Value("${tencent.cos.isp}")
    private String isp;
    @Value("${tencent.cos.netName}")
    private String netName;
    */
    @Autowired
    private CosProperties cosProperties;
    private COSClient cosClient = null;


    /**
     * @param file             要上传的文件
     * @param originalFilename 文件原始名称
     * @return 返回该文件在服务器上的路径
     */
    public String UploadUtils(File file, String originalFilename) {

        String bucketName = cosProperties.getBucketName();
        String regionCode = cosProperties.getRegion();
        String isp = cosProperties.getIsp();
        String netName = cosProperties.getNetName();
        String prootocol = cosProperties.getProotocol();


        log.debug("file：{}", file);
        String secretId = System.getenv("OSS_ACCESS_KEY_ID");
        String secretKey = System.getenv("OSS_ACCESS_KEY_SECRET");
        log.debug("secretId:{},secretKey:{}", secretId, secretKey);
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region("ap-chengdu");
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议，从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        cosClient = new COSClient(cred, clientConfig);
        log.debug("cosClient:{}", cosClient);

        // 指定文件将要存放的存储桶
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        //        String key = "img/picture.jpg";
        //        重新定义key
        //获取当前系统日期的字符串,格式为 yyyy/MM
        String dir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM"));
        //生成一个新的不重复的文件名
        log.debug("文件原始名称为：{}", originalFilename);
        String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        String key = dir + "/" + newFileName;
        log.info("{}上传文件名为：{}", LocalDateTime.now(), key);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        try {
            //上传文件
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        } finally {
            //关闭资源
            if (cosClient != null) {
                cosClient.shutdown();
            }
        }
        String url = prootocol + bucketName + netName + regionCode + isp + key;
        log.info("{}上传Cos文件服务器访问地址为：{}", LocalDateTime.now(), url);
        return url;
    }
}
